package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.config.common.R;
import com.itheima.reggie.config.constants.EmployeeConstant;
import com.itheima.reggie.entity.dto.EmployeeDto;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @Name EmployeeServiceImpl
 * @Author BaiXin
 * @Date 2022-10-28 15:09
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Override
    public R login(EmployeeDto employeeDto) {
        String username = employeeDto.getUsername();
        String password = employeeDto.getPassword();
        //参数判断
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return R.error("参数有误");
        }
        //根据用户名查用户
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, username);
        Employee employee = this.getOne(lqw);
        //判断用户是否为空
        if (null == employee) {
            return R.error("用户不存在");
        }
        //用户存在，判断密码
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!employee.getPassword().equals(md5Password)) {
            //密码不正确
            return R.error("用户名或密码错误");
        }
        //判断用户状态
        if (!EmployeeConstant.STATUS_OK.equals(employee.getStatus())) {
            //用户禁用
            return R.error("用户状态异常，请联系管理员");
        }
        //正常
        employee.setPassword("");
        return R.success(employee);
    }

    @Override
    public Employee selectByUsername(EmployeeDto employeeDto) {
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employeeDto.getUsername());
        Employee employee = this.getOne(lqw);
        return employee;
    }

}
